import { Component } from "react";

// import dataSource from '../../datasource.js';
import dataSource from '@/datasource.js';

// 高阶组件是参数为组件，返回值为新组件的函数
function wrap( WrappedComponent , selectData ) {

    class EnhancedComponent extends Component {
        constructor(props) {
          super(props);
          this.handleChange = this.handleChange.bind(this);
          this.state = {
            data: selectData( dataSource, props )
          };
        }
        componentDidMount() {
            dataSource.addChangeListener(this.handleChange);
        }
        componentWillUnmount() {
            dataSource.removeChangeListener(this.handleChange);
        }
        handleChange() {
          this.setState({
            data: selectData( dataSource, this.props )
          });
        }
        render() {
          // 将被包裹的组件直接渲染，并为其传递 props
          return <WrappedComponent data={this.state.data} {...this.props} />;
        }
    }

    return EnhancedComponent ;
}

export default wrap ;